const express = require('express');
const fs = require('fs');
const path = require('path');
const { exec } = require('child_process');
const ffmpeg = require('fluent-ffmpeg');

const app = express();
const PORT = process.env.PORT || 8000;
const dirname = path.resolve(); // 获取当前文件所在目录的绝对路径

/* 配置框架环境 S */

// 设置静态文件目录为项目的根目录
app.use(express.static(path.join(dirname)));

/* 配置框架环境 E */

app.use(express.json());

// 根目录
app.get('/', function(req, res) {
    res.sendFile(path.join(dirname, 'index.html'));
});

// 解析JSON格式的请求体
app.use(express.json());

// 视频转换路由
app.post('/convert-videos', (req, res) => {
    const directoryPath = req.body.directoryPath;

    // 检查路径是否存在
    if (!fs.existsSync(directoryPath)) {
        return res.status(404).send({ message: 'Directory does not exist' });
    }

    // 读取目录中的所有文件
    fs.readdir(directoryPath, (err, files) => {
        if (err) {
            console.error('Unable to scan directory:', err);
            return res.status(500).send({ message: 'Unable to scan directory' });
        }

        // 过滤出视频文件并转换格式
        files.forEach(file => {
            const fullFilePath = path.join(directoryPath, file);
            const fileExtension = path.extname(file).toLowerCase();

            // 检查文件是否为视频且不是MP4格式
            if (fileExtension !== '.mp4') {
                ffmpeg.ffprobe(fullFilePath, (err, metadata) => {
                    if (err) {
                        console.error('Error probing file:', fullFilePath, err);
                        return;
                    }

                    // 检查是否为视频流
                    const videoStream = metadata.streams.find(stream => stream.codec_type === 'video');
                    if (videoStream) {
                        const outputFilePath = path.join(directoryPath, path.basename(file, fileExtension) + '.mp4');
                        console.log('Starting conversion:', fullFilePath, '->', outputFilePath);
                        ffmpeg(fullFilePath)
                            .output(outputFilePath)
                            .on('end', () => {
                                console.log('Conversion finished:', outputFilePath);
                            })
                            .on('error', (err) => {
                                console.error('Error converting file:', fullFilePath, err);
                            })
                            .run();
                    }
                });
            }
        });

        res.send({ message: 'Video conversion started' });
    });
});

const server = app.listen(PORT, function() {
    var host = server.address().address;
    var port = server.address().port;

    console.log("Node.JS 服务器已启动，访问地址： http://%s:%s", host, port);

    // 构建要打开的URL
    var url = `http://localhost:${port}/index.html`;

    // 根据操作系统打开谷歌浏览器
    switch (process.platform) {
        case 'darwin': // macOS
            exec(`open -a "Google Chrome" ${url}`); // 使用谷歌浏览器打开URL
            break;
        case 'win32': // Windows
            exec(`start chrome ${url}`); // 使用谷歌浏览器打开URL
            break;
        case 'linux': // Linux
            exec(`google-chrome-stable ${url}`); // 使用谷歌浏览器打开URL
            break;
        default:
            console.log('无法识别的操作系统');
    }
});

